<?php
require 'db.php';

$settings_file = __DIR__ . '/settings.json';
$settings = file_exists($settings_file) ? json_decode(file_get_contents($settings_file), true) : ['title' => '私人网盘', 'registration_enabled' => true];
$site_title = $settings['title'];

if (!$settings['registration_enabled']) {
    header("Location: index.php");
    exit;
}

if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    if (!isset($_POST['csrf_token']) || $_POST['csrf_token'] !== $_SESSION['csrf_token']) {
        echo "<script>alert('CSRF 验证失败！'); history.back();</script>";
        exit;
    }
    $username = trim($_POST['username']);
    $password = $_POST['password'];

    if (strlen($username) < 3 || strlen($username) > 191) {
        echo "<script>alert('用户名长度必须在3到191个字符之间！'); history.back();</script>";
        exit;
    }
    if (strlen($password) < 6) {
        echo "<script>alert('密码至少6位！'); history.back();</script>";
        exit;
    }

    $check_stmt = $conn->prepare("SELECT id FROM users WHERE username = ?");
    $check_stmt->bind_param("s", $username);
    $check_stmt->execute();
    if ($check_stmt->get_result()->num_rows > 0) {
        echo "<script>alert('用户名已存在！'); history.back();</script>";
        exit;
    }

    $hashed_password = password_hash($password, PASSWORD_DEFAULT);
    $stmt = $conn->prepare("INSERT INTO users (username, password, role) VALUES (?, ?, 'user')");
    $stmt->bind_param("ss", $username, $hashed_password);
    if ($stmt->execute()) {
        echo "<script>alert('注册成功，请登录！'); window.location.href='login.php';</script>";
    } else {
        echo "<script>alert('注册失败：" . htmlspecialchars($stmt->error, ENT_QUOTES, 'UTF-8') . "'); history.back();</script>";
    }
    exit;
}
?>

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>注册 - <?= htmlspecialchars($site_title) ?></title>
    <link href="/assets/bootstrap/css/bootstrap.min.css" rel="stylesheet">
</head>
<body class="<?= $settings['theme'] === 'dark' ? 'bg-dark text-white' : '' ?>">
    <div class="container py-5">
        <h2>用户注册</h2>
        <form method="POST">
            <input type="hidden" name="csrf_token" value="<?= htmlspecialchars($_SESSION['csrf_token']) ?>">
            <div class="mb-3">
                <label for="username" class="form-label">用户名（3-191位）</label>
                <input type="text" class="form-control" id="username" name="username" required>
            </div>
            <div class="mb-3">
                <label for="password" class="form-label">密码（至少6位）</label>
                <input type="password" class="form-control" id="password" name="password" required>
            </div>
            <button type="submit" class="btn btn-primary">注册</button>
            <a href="login.php" class="btn btn-secondary">返回登录</a>
        </form>
    </div>
    <script src="/assets/bootstrap/js/bootstrap.bundle.min.js"></script>
</body>
</html>